package randomWalkWithRestartRecommender;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.regex.Pattern;

import Jama.Matrix;

import com.google.common.base.Charsets;

import com.google.common.io.Closeables;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.similarity.EuclideanDistanceSimilarity;
import org.apache.mahout.cf.taste.model.PreferenceArray;
import org.apache.mahout.common.iterator.FileLineIterable;

public final class GroupLensDataModel extends FileDataModel {

	private static final String COLON_DELIMITER = "::";
	private static final Pattern COLON_DELIMITER_PATTERN = Pattern.compile(COLON_DELIMITER);
	
	public GroupLensDataModel(File ratingsFile, String path) throws IOException {
		super(convertGLFile(ratingsFile, path));
	}

	private static File convertGLFile(File originalRatingsFile, String path) throws IOException {
		File resultFile = new File(path);
		if (resultFile.exists()) {
			resultFile.delete();
		}
		Writer writer = null;
		try {
			writer = new OutputStreamWriter(new FileOutputStream(resultFile),
					Charsets.UTF_8);
			for (String line : new FileLineIterable(originalRatingsFile, false)) {
				int lastDelimiterStart = line.lastIndexOf(COLON_DELIMITER);
				if (lastDelimiterStart < 0) {
					throw new IOException("Unexpected input format on line: " + line);
				}
				String subLine = line.substring(0, lastDelimiterStart);
				String convertedLine = COLON_DELIMITER_PATTERN.matcher(subLine).replaceAll(",");
				writer.write(convertedLine);
				writer.write('\n');
			}
		} catch (IOException ioe) {
			resultFile.delete();
			throw ioe;
		} finally {
			Closeables.closeQuietly(writer);
		}
		
		return resultFile;
	}

    public int maxItemNum() throws TasteException {
        int max = -1;
        for (LongPrimitiveIterator it = getItemIDs(); it.hasNext();) {
            long current = it.nextLong();
            if (max < current) {
                max = (int) current;
            }
        }
        return max;
    }

    public int maxUserNum() throws TasteException {
        int max = -1;
        for (LongPrimitiveIterator it = getUserIDs(); it.hasNext();) {
            long current = it.nextLong();
            if (max < current) {
                max = (int) current;
            }
        }
        return max;
    }

	@Override
	public String toString() {
		return "GroupLensDataModel";
	}
}
